package pl.polsl.mmm.projectcomm.util.bluetooth;

import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Message;
import android.os.Handler;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import pl.polsl.mmm.projectcomm.objects.state.BobState;

/**
 * Klasa reprezentuje nawiązane połączenie z drugim urządzeniem
 *
 * Created by michal on 28.12.14.
 */

public class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;
    private final Handler handler;
    private static Handler gameHandler;

    public static void setGameHandler (Handler pHandler) {
        gameHandler = pHandler;
    }

    public ConnectedThread(BluetoothSocket socket, Handler pHandler) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;
        handler = pHandler;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;

        threadMsg("Połączony");
    }

    public void run() {

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
//                byte [] buffer = new byte[738];
                byte [] buffer = new byte[1024];
                int bytes;
                bytes = mmInStream.read(buffer);

                sendMove(buffer);

            } catch (IOException e) {
                break;
            }
        }
    }

    // Po odebraniu danych przekazanie ich do obiektu
    private void sendMove(byte[] data) {

        if (gameHandler != null) {
            Message msgObj = gameHandler.obtainMessage();
            Bundle b = new Bundle();
            b.putByteArray("byteArray", data);
            msgObj.setData(b);
            gameHandler.sendMessage(msgObj);
        }
    }

    // Wyświetlenie informacji o nawiązaniu połączenia
    private void threadMsg(String msg) {

        if (!msg.equals(null) && !msg.equals("")) {
            Message msgObj = handler.obtainMessage();
            Bundle b = new Bundle();
            b.putString("message", msg);
            msgObj.setData(b);
            handler.sendMessage(msgObj);
        }
    }

    /* Call this from the main activity to send data to the remote device */
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

